// 初始化页面
document.addEventListener('DOMContentLoaded', function() {
    // 渲染频道列表
    renderChannels();

    // 绑定事件
    bindEvents();

    // 添加动画效果
    initAnimations();
});

// 修改后的OSS上传函数
async function uploadFileToOss(file, policy) {
    return new Promise((resolve, reject) => {
        const formData = new FormData();

        // 生成唯一文件名
        const timestamp = new Date().getTime();
        const random = Math.random().toString(36).substring(2, 8);
        const extension = file.name.split('.').pop();
        const fileName =timestamp+"_"+random+"."+extension;

        // 使用策略中的目录
        const key = policy.dir + fileName;

        formData.append('key', key);
        formData.append('policy', policy.policy);
        formData.append('OSSAccessKeyId', policy.accessid);
        formData.append('signature', policy.signature);
        formData.append('success_action_status', '200');
        formData.append('file', file);

        // 添加安全头
        if (policy['x-oss-security-token']) {
            formData.append('x-oss-security-token', policy['x-oss-security-token']);
        }
        formData.append('x-oss-object-acl', 'public-read');

        fetch(policy.host, {
            method: 'POST',
            body: formData
        })
            .then(response => {
                if (response.status === 200) {
                    // 构建文件URL
                    const fileUrl = policy.host+"/"+key;
                    console.log('头像上传成功:', fileUrl);
                    resolve(fileUrl);
                } else {
                    response.text().then(text => {
                        console.error('OSS上传错误:', text);
                        reject(`头像上传失败: ${response.status} - ${text}`);
                    });
                }
            })
            .catch(error => {
                console.error('上传错误:', error);
                reject(`上传错误: ${error.message}`);
            });
    });
}

// 渲染频道列表
function renderChannels() {
    const container = document.getElementById('channels-container');

    // 清空容器
    container.innerHTML = '';

    // 添加频道
    channelList.forEach(channel => {
        const channelElement = document.createElement('a');
        let cId=channel.cId;
        channelElement.href = contextPath+'/chat/1?email='+email+'&userName='+userName+'&userId='+userId;
        channelElement.className = 'channel';
        channelElement.innerHTML = `
            <i class="fas fa-hashtag"></i>
            <span>${channel.name}</span>
        `;

        container.appendChild(channelElement);
    });

    // 添加创建频道按钮
    const addButton = document.createElement('a');
    addButton.href = '#';
    addButton.className = 'add-channel';
    addButton.innerHTML = '<i class="fas fa-plus"></i>';
    addButton.id = 'add-channel';
    container.appendChild(addButton);
}

// 修改创建频道逻辑
document.getElementById('confirm-create-channel').addEventListener('click', async function() {
    const name = document.getElementById('channel-name').value;
    const category = document.getElementById('channel-category').value;
    const desc = document.getElementById('channel-desc').value;
    const coverFile = document.getElementById('channel-cover').files[0];

    if (!name.trim()) {
        showNotification('频道名称不能为空!', 'error');
        return;
    }
    try {
        // 1. 获取OSS上传凭证
        const policyResponse = await fetch(contextPath+'/oss/policy?dir=channel-covers/');
        const policy = await policyResponse.json();

        // 2. 上传封面到OSS
        let coverUrl = '';
        if (coverFile) {
            coverUrl = await uploadFileToOss(coverFile, policy);
        }

        // 3. 创建频道请求
        const formData1 = {
            name:name,
            cAvatar:coverUrl,
            userId: userId,
            sort: category,
            description:desc
        };

        const response = await fetch(contextPath+'/User/createChannel', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(formData1)
        });
        const result = await response.json();

        if (result.success) {
            alert("创建成功");
            document.getElementById("logo").click();
        } else {
            alert("创建失败")
            showNotification(result.message, 'error');
        }
    } catch (error) {
        console.error('创建频道失败:', error);
        showNotification('创建频道失败: ' + error.message, 'error');
    }
});

// 绑定事件
function bindEvents() {
    // 右上角按钮点击事件
    document.getElementById('messages').addEventListener('click', function(e) {
        e.preventDefault();
        toggleDropdown('messages-dropdown');
    });

    document.getElementById('follow').addEventListener('click', function(e) {
        e.preventDefault();
        toggleDropdown('follow-dropdown');
    });

    document.getElementById('search').addEventListener('click', function(e) {
        e.preventDefault();
        toggleDropdown('search-dropdown');
    });

    // 点击其他区域关闭下拉菜单
    document.addEventListener('click', function(e) {
        if (!e.target.closest('.nav-button-right') && !e.target.closest('.dropdown')) {
            document.querySelectorAll('.dropdown').forEach(dropdown => {
                dropdown.style.display = 'none';
            });
        }
    });

    // 创建频道按钮
    document.getElementById('add-channel').addEventListener('click', function(e) {
        e.preventDefault();
        // 重置表单
        document.getElementById('channel-name').value = '';
        document.getElementById('channel-cover').value = '';
        document.getElementById('channel-category').value = '射击游戏';
        document.getElementById('channel-desc').value = '';
        document.getElementById('cover-pw').innerHTML = '<i class="fas fa-image"></i><span>点击上传封面 (281x140)</span>';
        document.getElementById('create-channel-modal').style.display = 'flex';
    });

    // 封面上传预览
    document.getElementById('channel-cover').addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = function(event) {
                const preview = document.getElementById('cover-pw');
                preview.innerHTML = `<img src="${event.target.result}" alt="频道封面预览">`;
            };
            reader.readAsDataURL(file);
        }
    });

    // 取消创建频道
    document.getElementById('cancel-create-channel').addEventListener('click', function(e) {
        e.preventDefault();
        document.getElementById('create-channel-modal').style.display = 'none';
    });

    // 导航按钮点击事件
    document.getElementById('private-message').addEventListener('click', function(e) {
        e.preventDefault();
        // 这里可以跳转私信页面
        console.log('跳转私信页面');
    });

}

// 切换下拉菜单显示/隐藏
function toggleDropdown(id) {
    const dropdown = document.getElementById(id);
    const isVisible = dropdown.style.display === 'block';

    // 先隐藏所有下拉菜单
    document.querySelectorAll('.dropdown').forEach(d => {
        d.style.display = 'none';
    });

    // 切换当前下拉菜单
    dropdown.style.display = isVisible ? 'none' : 'block';
}

// 初始化动画效果
function initAnimations() {
    // 导航按钮悬停效果
    const navButtons = document.querySelectorAll('.nav-button, .nav-button-right');
    navButtons.forEach(button => {
        button.addEventListener('mouseenter', () => {
            button.style.transform = 'translateY(-3px)';
            button.style.boxShadow = '0 5px 15px rgba(0,0,0,0.2)';
        });

        button.addEventListener('mouseleave', () => {
            button.style.transform = '';
            button.style.boxShadow = '';
        });
    });

    // 频道悬停效果
    const channels = document.querySelectorAll('.channel');
    channels.forEach(channel => {
        channel.addEventListener('mouseenter', () => {
            channel.style.transform = 'translateX(5px)';
        });

        channel.addEventListener('mouseleave', () => {
            channel.style.transform = '';
        });
    });
}

// 修改通知函数以支持错误类型
function showNotification(message, type = 'success') {
    const notification = document.createElement('div');
    notification.className = `notification ${type}`;
    notification.innerHTML = `
    <i class="fas ${type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle'}"></i>
    <span>${message}</span>
  `;
    document.body.appendChild(notification);

    // 显示通知
    setTimeout(() => {
        notification.style.opacity = '1';
        notification.style.transform = 'translateY(0)';
    }, 10);

    // 3秒后隐藏并移除通知
    setTimeout(() => {
        notification.style.opacity = '0';
        notification.style.transform = 'translateY(20px)';
        setTimeout(() => {
            notification.remove();
        }, 300);
    }, 3000);
}
